package com.blog.zip.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;
import java.util.Objects;
@Slf4j
public class TokenUtil {

    private static final String  SING = "!Q@W34E%T6Y7";

    public static String getTokenUserId(){
        String zid = "";
        String token = Objects.requireNonNull(getRequest()).getHeader("B-Token");
//        System.out.println(token);
        zid = JWT.decode(token).getAudience().get(0);
        return zid;
    }
    private static HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        return requestAttributes == null ? null : requestAttributes.getRequest();
    }
    /**
     * 验证token的合法性
     * @param token
     * @return
     */


    public static DecodedJWT verify(String token) {
        //log.info("生成的token是{}", token);
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    public static String getToken(Map<String, Object> map) {

//        Date start = new Date();
//        long currentTime = System.currentTimeMillis() + 60 * 60 * 1000;
//        Date end = new Date(currentTime);
//        String token = "";
//        token = JWT.create()
//                .withAudience(user.getOid().toString())
//                .withIssuedAt(start)
//                .withExpiresAt(end)
//                .sign(Algorithm.HMAC256(SING));
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{

        });
        builder.withClaim("id",map.get("id").toString());
        builder.withClaim("username",map.get("username").toString());
        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
    }
}
